package com.qymerge.manage.system.controller;

import com.qymerge.manage.base.enums.ActiveTypes;
import com.qymerge.manage.base.ro.MetaOrgVersionRO;
import com.qymerge.manage.core.constant.BaseConstants;
import com.qymerge.manage.core.constant.ParamKey;
import com.qymerge.manage.core.controller.BaseController;
import com.qymerge.manage.core.enums.StatusTypes;
import com.qymerge.manage.core.bean.*;
import com.qymerge.manage.core.utils.*;
import com.qymerge.manage.system.dto.SysMenuDTO;
import com.qymerge.manage.system.dto.SysRoleDTO;
import com.qymerge.manage.system.dto.SysUserDTO;
import com.qymerge.manage.system.ro.SysMenuRO;
import com.qymerge.manage.system.ro.SysMenuRoleRO;
import com.qymerge.manage.system.ro.SysRoleRO;
import com.qymerge.manage.system.ro.SysUserRO;
import com.qymerge.manage.system.service.ISystemService;
import com.google.common.reflect.TypeToken;
import com.qymerge.manage.core.bean.*;
import com.qymerge.manage.core.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *<p>Title: SystemController</p>
 *<p>Description: 后台登录模块</p>
 *
 *@Author cong.zhang
 *@Version 1.0.0
 *@Date 2020/12/17
 *@Time 22:03
 */
@Controller
@RequestMapping(value = "sys")
public class SystemController extends BaseController {

    @Autowired
    private ISystemService systemService;

    /**
     * 后台管理系统-用户列表
     *
     * @param parameters
     * @param callback
     */
    @RequestMapping(value = "sysUserList")
    public void getSysUserList(HttpServletRequest request, HttpServletResponse response,

                               @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                               @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysUserRO sysUser = paramValue.getData();

        DataTableRO data = systemService.getSysUserList(sysUser, new PageRequest(common.getPage(), common.getSize()));
        PrintCodeUtils.printSuccess(response, data.build(), callback);
    }

    /**
     * 后台管理系统-获取用户信息
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/getSysUser")
    public void getSysUser(HttpServletRequest request, HttpServletResponse response,

                           @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                           @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysUserRO sysUser = paramValue.getData();

        SysUserRO data = systemService.getSysUser(sysUser);
        PrintCodeUtils.printSuccess(response, data, callback);
    }

    /**
     * 后台管理系统-用户保存
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/saveSysUser")
    public void saveSysUser(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysUserRO sysUser = paramValue.getData();

        sysUser.setPassword(MD5Utils.md5Hex(BaseConstants.PWD_DEFAULT + BaseConstants.PWD_SIGN));   // 设置初始值密码
        //sysUser.setUsername(sysUser.getPhone());

        // 设置默认值
        sysUser.setCreate_user_id(-1L);
        sysUser.setCreate_time(System.currentTimeMillis());
        sysUser.setStatus(StatusTypes.OnLine.getStatus());

        ActionResultRO actionResultRO = systemService.saveSysUser(sysUser);
        PrintCodeUtils.print(response, actionResultRO, callback);
    }

    /**
     * 后台管理系统-编辑用户信息
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/editSysUser")
    public void editSysUser(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysUserRO sysUser = paramValue.getData();

        sysUser.setUsername(sysUser.getPhone());
        sysUser.setCreate_user_id(-1L);
        sysUser.setCreate_time(System.currentTimeMillis());

        ActionResultRO actionResultRO = systemService.editSysUser(sysUser);
        PrintCodeUtils.print(response, actionResultRO, callback);
    }

    /**
     * 后台管理系统-删除用户
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/delSysUser")
    public void delSysUser(HttpServletResponse response, HttpServletRequest request,

                           @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                           @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {
        ParamValue<CommonIdsDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<CommonIdsDTO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        CommonIdsDTO commonIdsDTO = paramValue.getData();

        if (null == commonIdsDTO.getIds()) {
            RequestCheckUtils.checkNotFalse( false, "删除的用户ID不了为空！");
        }

        ActionResultRO actionResultRO = systemService.delSysUser(commonIdsDTO.getIds());
        PrintCodeUtils.printSuccess(response, actionResultRO, callback);
    }

    /**
     * 启用用户
     *
     * @param parameters
     * @param callback
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/sysUserOnline")
    public void online(@RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                       @RequestParam(defaultValue = ParamKey.In.empty) String callback,
                       HttpServletRequest request, HttpServletResponse response) throws Exception {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new com.google.gson.reflect.TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        SysUserRO ro = paramValue.getData();

        long id = ro.getId();
        RequestCheckUtils.checkNotEmpty(id, "ID必须");
        ActionResultRO resultRO = systemService.updateSysUserStatus(id, ActiveTypes.OnLine.getStatus(), ActiveTypes.OnLine.getDesc());
        PrintCodeUtils.print(response, resultRO, callback);
    }

    /**
     * 禁用用户
     *
     * @param parameters
     * @param callback
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/sysUserOffline")
    public void offline(@RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                        @RequestParam(defaultValue = ParamKey.In.empty) String callback,
                        HttpServletRequest request, HttpServletResponse response) throws Exception {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new com.google.gson.reflect.TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        SysUserRO ro = paramValue.getData();

        long id = ro.getId();
        RequestCheckUtils.checkNotEmpty(id, "ID必须");
        ActionResultRO resultRO = systemService.updateSysUserStatus(id, ActiveTypes.OffLine.getStatus(), ActiveTypes.OffLine.getDesc());
        PrintCodeUtils.print(response, resultRO, callback);
    }



    /**
     * 后台管理系统-菜单列表
     *
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/sysMenuList")
    public void sysMenuList(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysRoleRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysRoleRO>>() {
        }.getType());

        SysRoleRO sysRole = paramValue.getData();
        List<SysMenuRO> sysMenuData = systemService.getSysMenuList();

        //封装到MenuDto中
        List<SysMenuDTO> menuDtoList = new ArrayList<SysMenuDTO>();
        if (!CollectionUtils.isEmpty(sysMenuData)) {
            for (SysMenuRO sysMenu : sysMenuData) {
                SysMenuDTO dto = new SysMenuDTO();
                dto.setId(CommonUtil.getLongNotNull(sysMenu.getId()));
                dto.setParent_id(CommonUtil.getLongNotNull(sysMenu.getParent_id()));
                dto.setMenu_name(CommonUtil.getStringNotNullValue(sysMenu.getMenu_name()));
                dto.setMenu_path(CommonUtil.getStringNotNullValue(sysMenu.getMenu_path()));
                dto.setMenu_sort(CommonUtil.getLongNotNull(sysMenu.getMenu_sort()));
                dto.setIcon_cls(CommonUtil.getStringNotNullValue(sysMenu.getIcon_cls()));
                menuDtoList.add(dto);
            }
        }

        PrintCodeUtils.printSuccess(response, MenuUtils.formatMenuJson(menuDtoList), callback);
    }

    /**
     * 后台管理系统-根据菜单id获取菜单详情
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/getMenuById")
    public void getMenuById(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysMenuRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysMenuRO>>() {
        }.getType());
        SysMenuRO sysMenu = paramValue.getData();

        SysMenuRO result = systemService.getSysMenu(sysMenu);
        if (null != result) {
            PrintCodeUtils.printSuccess(response, result, callback);
        } else {
            PrintCodeUtils.printError(response, "菜单详情获取失败");
        }
    }

    /**
     * 后台管理系统-新增菜单
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/saveSysMenu")
    public void saveSysMenu(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysMenuRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysMenuRO>>() {
        }.getType());
        SysMenuRO sysMenu = paramValue.getData();

        sysMenu.setCreate_user_id(-1L);
        sysMenu.setCreate_time(System.currentTimeMillis());
        sysMenu.setStatus(StatusTypes.OnLine.getStatus());
        ActionResultRO data = systemService.saveSysMenu(sysMenu);
        PrintCodeUtils.printSuccess(response, data, callback);
    }

    /**
     * 后台管理系统-编辑菜单
     *
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/editSysMenu")
    public void editSysMenu(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysMenuRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysMenuRO>>() {
        }.getType());
        SysMenuRO sysMenu = paramValue.getData();

        ActionResultRO data = systemService.editSysMenu(sysMenu);
        PrintCodeUtils.printSuccess(response, data, callback);
    }

    /**
     * 后台管理系统-删除菜单
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/delSysMenu")
    public void delSysMenu(HttpServletRequest request, HttpServletResponse response,

                           @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                           @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysMenuRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysMenuRO>>() {
        }.getType());
        SysMenuRO sysMenu = paramValue.getData();

        ActionResultRO data = systemService.delSysMenu(sysMenu.getId());
        PrintCodeUtils.print(response, data, callback);
    }

    /**
     * 后台管理系统-角色列表
     *
     * @param parameters
     * @param callback
     * @return
     */
    @RequestMapping(value = "/sysRoleList")
    public void getSysRoleList(HttpServletRequest request, HttpServletResponse response,

                               @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                               @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysRoleRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysRoleRO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysRoleRO sysRole = paramValue.getData();

        DataTableRO data = systemService.getSysRoleList(sysRole, new PageRequest(common.getPage(), common.getSize()));
        PrintCodeUtils.printSuccess(response, data.build(), callback);
    }

    /**
     * 后台管理系统-新增角色
     *
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/saveSysRole")
    public void saveSysRole(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysRoleDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysRoleDTO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysRoleDTO sysRole = paramValue.getData();

        sysRole.setCreate_user_id(-1L);
        sysRole.setCreate_time(System.currentTimeMillis());
        sysRole.setStatus(StatusTypes.OnLine.getStatus());
        ActionResultRO obj = systemService.saveSysRole(sysRole);
        PrintCodeUtils.print(response, obj, callback);
    }

    /**
     * 后台管理系统-编辑角色信息
     *
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/editSysRole")
    public void editSysRole(HttpServletRequest request, HttpServletResponse response,

                            @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                            @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysRoleDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysRoleDTO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        SysRoleDTO sysRole = paramValue.getData();

        sysRole.setCreate_user_id(-1L);
        sysRole.setCreate_time(System.currentTimeMillis());
        sysRole.setStatus(StatusTypes.OnLine.getStatus());
        ActionResultRO obj = systemService.editSysRole(sysRole);
        PrintCodeUtils.print(response, obj, callback);
    }

    /**
     * 后台管理系统-删除角色
     *
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/delSysRole")
    public void delSysRole(HttpServletRequest request, HttpServletResponse response,

                           @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                           @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<CommonIdsDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<CommonIdsDTO>>() {
        }.getType());
        ParamCommon common = paramValue.getCommon();
        CommonIdsDTO commonIdsDTO = paramValue.getData();

        ActionResultRO obj = systemService.delSysRole(commonIdsDTO.getIds());
        PrintCodeUtils.printSuccess(response, obj, callback);
    }

    /**
     * 后台管理系统-角色编辑中加载菜单，动态勾选
     *
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/sysRoleMenuList")
    public void sysRoleMenuList(HttpServletResponse response, HttpServletRequest request,

                                @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                                @RequestParam(defaultValue = ParamKey.In.empty) String callback) {
        ParamValue<SysRoleRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysRoleRO>>() {
        }.getType());
        SysRoleRO sysRole = paramValue.getData();
        List<SysMenuRO> sysMenuData = systemService.getSysMenuList();

        //根据角色id获取角色可操作的菜单集合
        List<SysMenuRoleRO> menuRoleROS = systemService.getMenuRoleById(sysRole);

        List<String> existMenuIds = new ArrayList<String>();
        if (!CollectionUtils.isEmpty(menuRoleROS)) {
            for (SysMenuRoleRO sysMenuRole : menuRoleROS) {
                existMenuIds.add(String.valueOf(sysMenuRole.getMenu_id()));
            }
        }

        //封装到MenuDto中
        List<SysMenuDTO> menuDtoList = new ArrayList<SysMenuDTO>();
        if (!CollectionUtils.isEmpty(sysMenuData)) {
            for (SysMenuRO sysMenu : sysMenuData) {
                SysMenuDTO dto = new SysMenuDTO();
                dto.setId(CommonUtil.getLongNotNull(sysMenu.getId()));
                dto.setParent_id(CommonUtil.getLongNotNull(sysMenu.getParent_id()));
                dto.setMenu_name(CommonUtil.getStringNotNullValue(sysMenu.getMenu_name()));
                dto.setMenu_path(CommonUtil.getStringNotNullValue(sysMenu.getMenu_path()));
                dto.setMenu_sort(CommonUtil.getLongNotNull(sysMenu.getMenu_sort()));
                // 这里目前只针对二级菜单，多余二级的，要根据children集合来判断
                if (existMenuIds.contains(String.valueOf(dto.getId()))) {
                    dto.setChecked("true");
                }
                menuDtoList.add(dto);
            }
        }

        PrintCodeUtils.printSuccess(response, MenuUtils.formatMenuJson(menuDtoList), callback);
    }

    /**
     * 后台管理系统-根据用户id获取角色集合
     *
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getRolesByUserId")
    public void getRolesByUserId(HttpServletRequest request, HttpServletResponse response,

                                 @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                                 @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {
        ParamValue<SysUserRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserRO>>() {
        }.getType());
        SysUserRO sysUser = paramValue.getData();

        ActionResultRO data = systemService.getRolesByUserId(sysUser);
        PrintCodeUtils.printSuccess(response, data.getResultMap(), callback);
    }

    /**
     * 后台管理系统-分配角色
     *
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editUserRole")
    public void editUserRole(HttpServletRequest request, HttpServletResponse response,

                             @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                             @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {
        ParamValue<SysUserDTO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysUserDTO>>() {
        }.getType());
        SysUserDTO userDto = paramValue.getData();

        userDto.setCreate_user_id(Long.valueOf(-1L));
        userDto.setCreate_time(System.currentTimeMillis());
        userDto.setStatus(StatusTypes.OnLine.getStatus());
        ActionResultRO obj = systemService.editUserRole(userDto, new PageRequest());
        PrintCodeUtils.print(response, obj, callback);
    }

    /**
     * 获取页面头部菜单导航
     *
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/showMenuHead")
    public void showMenuHead(HttpServletRequest request, HttpServletResponse response,

                             @RequestParam(defaultValue = ParamKey.In.dlt_parameters) String parameters,
                             @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {
        ParamValue<SysMenuRO> paramValue = GsonUtil.json2T(parameters, new TypeToken<ParamValue<SysMenuRO>>() {
        }.getType());
        SysMenuRO sysMenu = paramValue.getData();

        ReturnMap obj = systemService.showMenuHead(sysMenu.getId());
        PrintCodeUtils.printSuccess(response, obj, callback);
    }

    /**
     * 获取环境配置
     *
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping(value = "/getConfig")
    public void getConfig(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(defaultValue = ParamKey.In.empty) String callback) throws Exception {

        Map<String, Object> obj = new LinkedHashMap<String, Object>();
        obj.put("api_domain", Env.apiDomain);
        obj.put("m_domain", Env.mDomain);

        PrintCodeUtils.printSuccess(response, obj, callback);
    }


}
